package com.agynamix.scala.mi

import _root_.java.io.File
import _root_.javax.script.ScriptException

/**
 * Created by IntelliJ IDEA.
 * User: tuhlmann
 * Date: 05.04.2010
 * Time: 19:12:07
 * To change this template use File | Settings | File Templates.
 */

class MovieFileProcessor extends MediaFileProcessor {

  def process(mediaFile: File): ITunesProcessResult = {
    val name = removeExtension(mediaFile.getName())
    val genre = mediaFile.getParentFile().getName()
    val appleFileName = mediaFile.getAbsolutePath() // .replace('/', ':');
    println("Found: " + appleFileName + "; name=" + name + ", genre=" + genre)

    try {
      return addMovieToItunes(appleFileName, name, genre)
    } catch {
    case e => println("Could not import media file: "+appleFileName+", Error: "+e.getMessage)
      return new ITunesProcessResult(false, "")
    }

  }


  @throws(classOf[ScriptException])
  def addMovieToItunes(appleFileName: String, name: String, genre: String): ITunesProcessResult = {
    val sb = new StringBuilder()
    sb.append("set iTunesFile to POSIX file \"" + appleFileName + "\"\n")
    sb.append("tell application \"iTunes\"\n")
    sb.append("copy (add iTunesFile) to newMovie\n")
    sb.append("set (genre of newMovie) to \"" + genre + "\"\n")
    sb.append("set (name of newMovie) to \"" + name + "\"\n")
    sb.append("set (video kind of newMovie) to movie\n")
    sb.append("set pid to newMovie's persistent ID\n")
    sb.append("end tell")

    new ITunesProcessResult(true, scriptEngine.eval(sb.toString()).toString)
  }



}